#! python3
# -*- coding: UTF-8 -*-
# @Time    : 2025/05/26
# @Author  : AndrewWay
# @version : 1.0
# @notes   ：
import os
import random
import sys
import time

import pyautogui
import pyperclip

import get_root_path
from datetime import datetime
# 桌面自动化
from uiautomation import uiautomation as auto
from loguru import logger
from common.db import DB

today_log = datetime.now().strftime("%Y-%m-%d")
if not os.path.exists('log'):
    os.mkdir('log')
logger.remove()
logger.add(
    sink=sys.stdout,
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> {level}: {message}",
    level="DEBUG"
)
logger.add(
    sink=f"{os.path.join(get_root_path.get_base_path(), 'log', f'{today_log}.log')}",
    format="{time:YYYY-MM-DD HH:mm:ss} {level}: {message}",
    level="DEBUG"
)


class Base:
    def __init__(self):
        self.db: DB = DB()
        self.logger = logger
        self.auto = auto
        self.wechat = auto.WindowControl(searchDepth=10, Name="微信",
                                         Compare=lambda c, d: not c.IsOffscreen)

    # 初始化微信窗口
    def init_weChat(self):
        # 设置为当前活动窗口
        self.wechat.SetActive()
        # 窗口最大化
        self.wechat.Maximize()

    # 分配任务
    def assign_tasks(self, monitor_obj_list,
                     keyword_list,
                     target_user_list,
                     group_name1,
                     group_name2):
        """
        :param monitor_obj_list: 监控的对象
        :param keyword_list: 关键词列表
        :param target_user_list: 特定的监控好友
        :param group_name1: 群聊1
        :param group_name2: 群聊2
        :return:
        """
        from scripts.wechat.get_wechat_msg import GetWeChatMsg

        for item in monitor_obj_list:
            """
            :param item:包含了监控对象和特定的监控好友
            """
            # 监控群主的所有发言
            if isinstance(item, dict) and group_name1 in item.keys():
                time.sleep(random.uniform(1.5, 3.0))
                # self.init_weChat()
                self.logger.info(f'正在获取【{group_name1}】'
                                 f'群主【{next(iter(item.values()))}】所有的发言消息')
                GetWeChatMsg().open_chat_wnd_and_get_msg(item=item,
                                                         group_name=group_name1,
                                                         keyword_list=None)
            # 监控群主2的发言是否触发了关键词
            elif isinstance(item, dict) and group_name2 in item.keys():
                time.sleep(random.uniform(1.9, 3.4))
                # self.init_weChat()
                self.logger.info(f'正在获取【{group_name2}】'
                                 f'群主【{next(iter(item.values()))}】的关键词消息')
                GetWeChatMsg().open_chat_wnd_and_get_msg(item=item,
                                                         group_name=group_name2,
                                                         keyword_list=keyword_list)
            # 监控特定的好友发言
            elif item in target_user_list:
                # self.init_weChat()
                self.logger.info(f'正在获取【{item}】的消息')
                GetWeChatMsg().open_chat_wnd_and_get_msg(item=item,
                                                         group_name=None,
                                                         keyword_list=None)


            # chat_window = None
            # # try:
            # #     chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=item, searchWaitTime=3)
            # # except Exception as e:
            # #     chat_window = None
            # # 聊天框已经打开的情况
            # if chat_window:
            #     chat_window.SetActive()
            #     chat_window.Maximize()
            #     GetWeChatMsg().get_msg(keyword_list, item)
            # else:
            #     # 聊天框未打开的情况
            #     self.logger.info('点击 搜索')
            #     search = self.wechat.EditControl(Name="搜索")
            #     search.Click()
            #     time.sleep(2)
            #     # 复制group的文本
            #     pyperclip.copy(item)
            #     # 粘贴
            #     pyautogui.hotkey('ctrl', 'v')
            #     time.sleep(2)
            #     pyautogui.press('enter')
            #     group_item = self.auto.TextControl(Name=f"{item}")
            #     group_item.DoubleClick()
            #     time.sleep(2)
            #     chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=f"{item}")
            #     chat_window.SetActive()
            #     chat_window.Maximize()
            #     GetWeChatMsg().get_msg(keyword_list, item)

    # 启动程序
    def start(self, monitor_obj_list,
              keyword_list,
              target_user_list,
              group_name1,
              group_name2):
        # self.init_weChat()
        # 分配任务
        self.assign_tasks(monitor_obj_list,
                          keyword_list,
                          target_user_list,
                          group_name1,
                          group_name2)

    # 打开指定的聊天窗口
    def open_chat_window(self, target_chat):
        """
        :param target_chat: 打开目标群聊或好友聊天窗口
        :return:
        """
        self.init_weChat()
        # 聊天框未打开的情况
        self.logger.info('点击 搜索')
        search = self.wechat.EditControl(Name="搜索") # 编辑控件
        search.Click()
        time.sleep(2)
        # 复制group的文本
        pyperclip.copy(target_chat)
        # 粘贴
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(2)
        pyautogui.press('enter')
        self.slide2top()
        group_item = self.auto.TextControl(Name=f"{target_chat}")
        group_item.DoubleClick()
        time.sleep(2)
        chat_window = self.auto.WindowControl(ClassName="ChatWnd",
                                              Name=f"{target_chat}")
        chat_window.SetActive()
        chat_window.Maximize()

    # 滑动到聊天列表的顶部
    def slide2top(self):
        chat_list = self.wechat.ListControl(searchDepth=10, Name="会话")
        if chat_list.Exists():
            # 将鼠标移动到列表控件的中心位置
            rect = chat_list.BoundingRectangle
            center_x = (rect.left + rect.right) // 2
            center_y = (rect.top + rect.bottom) // 2
            pyautogui.moveTo(center_x, center_y)
            for _ in range(30):
                pyautogui.scroll(200)
        else:
            self.logger.warning("未找到名为'会话'的列表控件")

    # 滑动屏幕
    def slide_screen(self):
        self.logger.info("正在初始化聊天内容")
        for _ in range(20):
            pyautogui.scroll(300)
        for _ in range(20):
            pyautogui.scroll(-300)
